import React, {
    Component,
} from 'react';
import {
    StyleSheet,
    Text,
    View,
    Platform,
    Dimensions,
    TouchableOpacity,
    Image,
    Alert,
    FlatList,
    TextInput,
    Linking,
    ScrollView,
    Switch,
    DeviceEventEmitter,
} from 'react-native';
import AndroidModule from 'src/utils/AndroidConnent'
import Loading from "../../utils/Loading";
import HttpUtils from '../../utils/HttpUtils';
import HttpUrls from '../../utils/HttpUrls';
import Header from "../../components/header";
import PublishCarArrow from '../car/publishCar/components/PublishCarArrow';
import PublishCarTextInput from '../car/publishCar/components/PublishCarTextInput';
import Constant from '../../utils/Constant'//全局变量
import { ToastToUser } from '../../utils/CustomToast';
import Picker from 'react-native-picker'
import DatePickerPart from '../../components/Tool/DatePickerPart'
import { getImgUrl } from '../../utils/ComFunction'
import { conditionObjWithType } from '../../utils/Conditions'
import { CarSaleStatus } from '../../utils/Enum'
import AsyncImage from '../../components/image/AsyncImage';


let navigation

export default class CarDetectionPage extends Component {
    constructor(props) {
        super(props);
        let carId = this.props.route && this.props.route.params && this.props.route.params.carId ? this.props.route.params.carId : ''
        this.state = {
            carId: carId,
            data: {},
            detectionTypeArray: '',
            detectionType: '',//检测类型
            detectionTypeValue: ['全车检测'],
            inspectorUserId: '', //检测师id
            inspectorUserName: '', //检测师
            detectionPrice: '10', //检测价格
            isJoin: false,
            saleStatus: '',
            type: this.props.route && this.props.route.params && this.props.route.params.type ? this.props.route.params.type : '',//1复检
        }
    }

    componentDidMount() {
        this.getOwnCarDetails()
        this.getDetectionByType()

        if(this.state.type == '1'){
            this.setState({
                inspectorUserName:'系统分发',
                inspectorUserId:0
            })
        }
    }

    getDetectionByType() {
        let param = {
            type: 'DetectionType'
        }
        HttpUtils.getRequest(HttpUrls.getDictByType, param)
            .then((result) => {
                let data = result.data
                this.setState({
                    detectionTypeArray: data,
                })
            })
            .catch((error) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
            });
    }

    getOwnCarDetails() {
        let param = {
            carId: this.state.carId
        }
        if (this.Loading) {
            this.Loading.show();
        }
        let url = ''
        if (this.state.saleStatus == CarSaleStatus.CarSaleStatusSaled) {
            url = HttpUrls.getOwnSoldCarDetails
        } else {
            url = HttpUrls.getOwnCarDetails
        }
        HttpUtils.getRequest(url, param)
            .then((result) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
                if (result.code == 0) {
                    let data = result.data
                    let isJoin = (data.joinQuotationCenter && Constant.userInfo.isFranchisee) || (data.joinUnion && !Constant.userInfo.isFranchisee)
                    this.setState({
                        data,
                        isJoin,
                    })
                } else {
                    this.setState({
                        saleStatus: CarSaleStatus.CarSaleStatusSaled
                    }, function () {
                        this.getOwnCarDetails()
                    })
                }
            })
            .catch((error) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
            });
    }

    render() {
        navigation = this.props.navigation;
        return (
            <View style={styles.container}>
                <Header navigation={navigation} Title={'检测下单'}></Header>
                <ScrollView
                    style={{ flex: 1 }}
                >
                    <View style={styles.contentContainer}>

                        <View style={styles.carInfoBox}>
                            <View style={styles.carBox}>
                                <AsyncImage style={styles.carImg} source={{ uri: this.state.data && this.state.data.carPics ? getImgUrl(this.state.data.carPics[0].picUrl) : '' }} defaultSource={require('source/image/comm/sc_default.png')} />
                                <View style={styles.carRightBox}>
                                    <Text style={styles.brandText} numberOfLines={1}>{this.state.data && this.state.data.seriesName ? this.state.data.seriesName + ' ' + this.state.data.speciesName : ''}</Text>
                                    <Text style={styles.dateText}>{(this.state.data.registerDate && this.state.data.registerDate.length >= 2 ? this.state.data.registerDate.split('-')[0] + '-' + this.state.data.registerDate.split('-')[1] : '') + (this.state.data.mileage ? (' | ' + (this.state.data.mileage / 10000).toFixed(2) + '万公里') : '')}</Text>
                                    <Text style={styles.vinText} numberOfLines={1}>{this.state.data && this.state.data.vcode ? ('VIN：' + this.state.data.vcode) : ''}</Text>
                                </View>
                            </View>
                            {this.state.type == '1' ?

                                null
                                :
                                <View style={styles.markBox}>
                                    {/* 库存状态 */}
                                    {
                                        this.state.data.storeStatus ?
                                            <View style={styles.labelItemBox}>
                                                <Text style={styles.labelText}>{conditionObjWithType('storeStatus')[this.state.data.storeStatus]}</Text>
                                            </View>
                                            :
                                            null
                                    }
                                    {/* 库龄 */}
                                    {
                                        this.state.data.purchaseDate ?
                                            <View style={styles.labelItemBox}>
                                                <Text style={styles.labelText}>{'库存' + this.getDaysBetweenDates(this.state.data.purchaseDate) + '天'}</Text>
                                            </View>
                                            :
                                            null
                                    }
                                    {/* 收购性质，在全款的时候隐藏 */}
                                    {
                                        this.state.data.purchaseType && this.state.data.purchaseType != 1 ?
                                            <View style={styles.labelItemBox}>
                                                <Text style={styles.labelText}>{conditionObjWithType('purchaseType')[this.state.data.purchaseType]}</Text>
                                            </View>
                                            :
                                            null
                                    }
                                    {/* 已上架/未上架 */}
                                    <View style={[styles.labelItemBox, { backgroundColor: this.state.isJoin ? '#FFF7E0' : '#F4F4F4' }]}>
                                        <Text style={[styles.labelText, { color: this.state.isJoin ? '#FF7B00' : '#666' }]}>{this.state.isJoin ? '已上架' : '未上架'}</Text>
                                    </View>

                                    {/* 已预订 */}
                                    {
                                        this.state.data.saleStatus == 3 ?
                                            <View style={[styles.labelItemBox, { backgroundColor: '#FFF7E0' }]}>
                                                <Text style={[styles.labelText, { color: '#FF7B00' }]}>已预订</Text>
                                            </View>
                                            :
                                            null
                                    }

                                    {/* 检测状态 */}
                                    {
                                        this.state.data.detectionStatus ?
                                            <View style={[styles.labelItemBox, { backgroundColor: this.state.data.detectionStatus == 3 ? '#FFF7E0' : '#F4F4F4' }]}>
                                                <Text style={[styles.labelText, { color: this.state.data.detectionStatus == 3 ? '#FF7B00' : '#666' }]}>{conditionObjWithType('carDetectionStatus')[this.state.data.detectionStatus]}</Text>
                                            </View>
                                            :
                                            <View style={styles.labelItemBox}>
                                                <Text style={styles.labelText}>{'未自检'}</Text>
                                            </View>
                                    }
                                </View>
                            }

                        </View>

                        <PublishCarArrow
                            name={'检测类型'}
                            content={this.state.detectionType ? this.state.detectionTypeValue[0] : ''}
                            clickHandle={() => {
                                this.showDetectionPicker()
                            }}
                        />

                        <PublishCarArrow
                            name={'检测师'}
                            content={this.state.inspectorUserName}
                            clickHandle={() => {
                                navigation.navigate('SellerSelectPage', {
                                    isDetection: true,
                                    selectedUserId: this.state.inspectorUserId,
                                    selectCompletion: (item) => {
                                        this.setState({
                                            inspectorUserId: item.userId,
                                            inspectorUserName: item.fullname
                                        })
                                        navigation.goBack()
                                    }
                                })
                            }}
                        />

                        <PublishCarTextInput
                            name={'检测费用'}
                            hideSepline={true}
                            value={this.state.detectionPrice + '元'}
                            disable={true}
                        />

                    </View>

                </ScrollView>

                <View style={[styles.bottomBox, { height: 60 + Constant.bottomHeight }]}>
                    <TouchableOpacity
                        style={styles.submitBox}
                        activeOpacity={0.8}
                        onPress={() => {
                            this.submit()
                        }}
                    >
                        <Text style={styles.submitText}>提交检测</Text>
                    </TouchableOpacity>
                </View>

                <Loading onRef={(ref) => (this.Loading = ref)} />

                <DatePickerPart type={this.state.dateTypeMode} defaultDate={this.state[this.state.tradeDate]} show={this.state.showDatePicker} changeState={
                    (val) => { // 时间选择组件显示与否
                        this.setState({
                            showDatePicker: val,
                        })
                    }
                } changeDate={(date) => {
                    this.setState({
                        tradeDate: date,
                    })
                }} />

            </View>
        )
    }

    getDaysBetweenDates(dateString) {
        let pastDate = new Date(dateString);
        let currDate = new Date()
        const timeDiff = Math.abs(currDate.getTime() - pastDate.getTime());
        // 将毫秒转换为天数
        return Math.floor(timeDiff / (1000 * 60 * 60 * 24)) + 1;
    }

    //输入框内容输入
    changeText(type, val) {
        this.setState({
            [type]: val
        })
    }

    showDetectionPicker() {
        let data = []
        this.state.detectionTypeArray.map((item) => {
            data.push(item.desc)
        })
        let datas = this.state.detectionTypeArray
        Picker.init({
            pickerData: data,
            selectedValue: this.state.detectionTypeValue,
            // pickerBg:[255, 0 ,0, 1],
            pickerFontColor: [0, 0, 0, 1],
            pickerCancelBtnText: '取消',
            pickerCancelBtnColor: [134, 136, 137, 1],
            pickerConfirmBtnText: '确认',
            pickerTitleText: '',
            pickerToolBarBg: [255, 255, 255, 1],
            pickerBg: [255, 255, 255, 1],

            onPickerConfirm: data => {
                let value = '';
                for (var i = 0; i < datas.length; i++) {
                    if (datas[i].desc == data) {
                        value = datas[i].code
                    }
                }
                this.setState({
                    detectionTypeValue: data,
                    detectionType: value
                })
            },
            onPickerCancel: data => {

            },
            onPickerSelect: data => {
                console.log('data = ', data)
            }
        });
        Picker.show();
    }

    submit() {
        if (this.state.detectionType == '') {
            ToastToUser('请选择检测类型')
            return
        }
        if (this.state.inspectorUserId === '') {
            ToastToUser('请选择检测师')
            return
        }

        let params = {
            merchantId: Constant.userInfo.merchantId,
            inspectorUserId: this.state.inspectorUserId,
            vcode: this.state.data.vcode,
            detectionType: this.state.detectionType,
            detectionStatus: this.state.data.detectionStatus,
            operator: Constant.userInfo.fullname,
            carId: this.state.carId,
            carName: this.state.data.seriesName + ' ' + this.state.data.speciesName,
        }

        if (this.Loading) {
            this.Loading.show('提交中...');
        }
        HttpUtils.postRequest(HttpUrls.createDetectionOrder, params)
            .then((result) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
                if (result.code == 0) {
                    ToastToUser('提交成功!')
                    if (this.props.route.params && this.props.route.params.completion) {
                        setTimeout(() => {
                            navigation.goBack()
                            this.props.route.params.completion()
                        }, 500);
                    }else {
                        navigation.goBack()
                    }
                } else {
                    ToastToUser(result.msg ? result.msg : result.statusText)
                }
            })
            .catch((error) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
            });

    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F9F9F9',
    },
    sepLine: {
        width: '100%',
        height: 10
    },
    contentContainer: {
        width: '100%',
        flexDirection: 'column',
        backgroundColor: '#fff',
        paddingHorizontal: 16,

    },
    carInfoBox: {
        width: '100%',
        paddingVertical: 12,
        flexDirection: 'column',

    },
    carBox: {
        flexDirection: 'row',

    },
    carImg: {
        width: 120,
        height: 90,
        borderRadius: 4,
        backgroundColor: '#f9f9f9'
    },
    carRightBox: {
        height: 90,
        flex: 1,
        marginLeft: 12,
        flexDirection: 'column',
        justifyContent: 'flex-start',
        alignItems: 'flex-start'
    },
    brandText: {
        marginTop: 5,
        color: '#333',
        fontSize: 14,
    },
    dateText: {
        marginTop: 5,
        color: '#666',
        fontSize: 14,
    },
    vinText: {
        marginTop: 24,
        color: '#333',
        fontSize: 14,
        lineHeight: 20,
    },
    markBox: {
        marginTop: 8,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'flex-start',
    },
    labelItemBox: {
        marginRight: 6,
        paddingHorizontal: 10,
        height: 21,
        flexDirection: 'row',
        alignItems: 'center',
        borderRadius: 2,
        backgroundColor: '#F4F4F4'
    },
    labelText: {
        fontSize: 12,
        color: '#666'
    },


    bottomBox: {
        backgroundColor: '#fff',
        width: '100%',
        paddingTop: 7,
        paddingHorizontal: 15,
        flexDirection: 'column',
        alignItems: 'center'
    },
    submitBox: {
        width: '100%',
        height: 46,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#FFE000',
        borderRadius: 23
    },
    submitText: {
        color: '#333333',
        fontSize: 16
    }

})